<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能陪伴监护端</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f6f9;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            padding:10px;
        }
        .container {
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 600px;
            padding: 20px;
            margin-bottom:10px;
        }
        .map-group {
            position: relative;
        }
        #map {
            height: 300px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .notification {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: white;
            color: red;
            font-weight: bold;
            text-align: center;
            font-size: 18px;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            display: none;
        }
        .info-box {
            position: absolute;
            bottom: 18px;
            background-color: white;
            color: #333;
            font-weight: bold;
            text-align: center;
            font-size: 16px;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }
        .height-info {
            left: 20px;
        }
        .time-info {
            right: 20px;
        }
        h1 {
            text-align: center;
            color: #4A90E2;
            margin-bottom: 20px;
        }
        h2 {
            text-align: center;
            color: #4A90E2;
            margin-bottom: 20px;
        }
        .form-group {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        label {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
        }
        input[type="range"] {
            width: 100%;
            margin-bottom: 10px;
        }
        #radiusValue {
            font-size: 16px;
            color: #333;
            display: inline-block;
            margin-top: 5px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4A90E2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin: 5px;
        }
        button:hover {
            background-color: #357ABD;
        }
        button:active {
            background-color: #2E6A9C;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能陪伴监护端</h1>

        <div class="map-group">
            <div id="map"></div>
            <div class="height-info info-box" id="heightInfo">对象高度: 无</div>
            <div class="time-info info-box" id="timeInfo">更新时间: 无</div>
            <div class="notification" id="notification">警告：监护对象已超出围栏范围！</div>
        </div>

        <div class="form-group">
            <label for="radiusInput">电子围栏半径: <span id="radiusValue">1 千米</span> </label>
            <input type="range" id="radiusInput" min="500" max="3000" value="1000" step="100" />
            <div>
                <button onclick="setGeofence()">设置电子围栏</button>
                <button onclick="removeGeofence()">取消电子围栏</button>
            </div>
        </div>
    </div>
    <div class="container">
        <img id="dynamicPhoto" src="http://47.119.40.164/files/photo.jpg?time=" alt="照片" style="width: 100%; height: auto; margin-bottom: 10px">
        <div class="form-group">
            <button onclick="captureSnapshot()">一键抓拍</button>
        </div>
    </div>

    <script>
        // 动态更新图片 URL，通过时间戳确保每次加载新图片
        function updateImage() {
            const imgElement = document.getElementById('dynamicPhoto');
            imgElement.src = 'http://47.119.40.164/files/photo.jpg?time=' + new Date().getTime();
        }

        // 页面加载时更新图片
        window.onload = function() {
            updateImage();
        }

        // 初始化地图
        const map = L.map('map').setView([0, 0], 13); // 初始默认位置

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
        }).addTo(map);

        // 监护对象标记
        let marker = L.marker([0, 0]).addTo(map).bindPopup('监护对象当前位置');

        // 电子围栏
        let geofenceRadius = 1000; // 默认1km
        let geofenceCenter = null;
        let geofenceCircle = null;

        // 获取滑动条和显示的文本
        const radiusInput = document.getElementById('radiusInput');
        const radiusValue = document.getElementById('radiusValue');

        // 显示当前滑动条值
        radiusInput.addEventListener('input', function() {
            radiusValue.textContent = radiusInput.value / 1000 + " 千米";
        });

        // 设置电子围栏
        function setGeofence() {
            geofenceRadius = parseInt(radiusInput.value, 10) || 1000;

            map.once('click', function (e) {
                geofenceCenter = [e.latlng.lat, e.latlng.lng];

                if (geofenceCircle) {
                    geofenceCircle.setLatLng(geofenceCenter).setRadius(geofenceRadius);
                } else {
                    geofenceCircle = L.circle(geofenceCenter, {
                        radius: geofenceRadius,
                        color: '#FF5733',
                        fillColor: '#FF5733',
                        fillOpacity: 0.4
                    }).addTo(map);
                }

                checkGeofence(marker.getLatLng());
            });
        }

        // 取消电子围栏
        function removeGeofence() {
            if (geofenceCircle) {
                map.removeLayer(geofenceCircle);
                geofenceCircle = null;
                document.getElementById("notification").style.display = "none";
            }
        }

        // 检查监护对象是否超出围栏
        function checkGeofence(position) {
            if (!geofenceCircle || !geofenceCenter) return;

            const distance = L.latLng(geofenceCenter).distanceTo(position);

            if (distance > geofenceRadius) {
                document.getElementById("notification").style.display = "block";
            } else {
                document.getElementById("notification").style.display = "none";
            }
        }

        // 连接 MQTT
        const mqttClient = mqtt.connect('wss://n12ebcd2.ala.cn-hangzhou.emqxsl.cn:8084/mqtt', {
            username: 'emqx',
            password: '123456'
        });

        // 发布抓拍指令到 MQTT
        function captureSnapshot() {
            const commandMessage = {
                action: 'capture_snapshot'
            };

            mqttClient.publish('command', JSON.stringify(commandMessage), { qos: 1 }, (err) => {
                if (err) {
                    console.error("Error sending capture command:", err);
                } else {
                    console.log("Capture command sent successfully.");
                    // 延迟 0.5 秒后刷新图片
                    setTimeout(updateImage, 500);
                }
            });
        }

        mqttClient.on('connect', () => {
            console.log('Connected to MQTT Broker');
            mqttClient.subscribe('message');
        });

        mqttClient.on('message', (topic, message) => {
            console.log("Received message:", message.toString());

            try {
                let payload = JSON.parse(message.toString());
                let newLat = parseFloat(payload.lat);
                let newLng = parseFloat(payload.lon);
                let newHeight = payload.msl; // 提取高度信息
                let newTime = payload.beijing_time_str; // 提取时间信息

                if (!isNaN(newLat) && !isNaN(newLng)) {
                    // 更新标记位置，但不修改视角和缩放级别
                    marker.setLatLng([newLat, newLng])
                        .bindPopup('监护对象当前位置')
                        .openPopup();

                    // 更新高度信息显示
                    document.getElementById("heightInfo").textContent = "对象高度: " + newHeight;
                    document.getElementById("timeInfo").textContent = "更新时间: " + newTime;

                    // 只更新电子围栏检查
                    checkGeofence({ lat: newLat, lng: newLng });
                } else {
                    console.error("Invalid coordinates received:", payload);
                }
            } catch (error) {
                console.error("Error parsing JSON:", error);
            }
        });
    </script>
</body>
</html>
